package com.cctc.rds.nrpc.core.client.helper;

import com.cctc.rds.nrpc.core.protocol.message.Message;
import io.netty.channel.ChannelPromise;

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;

public class ChannelPromiseHolder {
    private static final Map<String, Map.Entry<ChannelPromise, Message>> cache = new HashMap<>();

    private ChannelPromiseHolder() {
    }

    public static void putEntry(String txid, ChannelPromise promise) {
        cache.put(txid, new AbstractMap.SimpleEntry<>(promise, null));
    }

    public static Map.Entry<ChannelPromise, Message> getEntry(String txid) {
        return cache.get(txid);
    }

    public static void removeEntry(String txid) {
        cache.remove(txid);
    }

    public static void completePromise(String txid, Message message) {
        if (!cache.containsKey(txid)) return;
        Map.Entry<ChannelPromise, Message> entry = cache.get(txid);
        if (entry == null) return;
        ChannelPromise promise = entry.getKey();
        if (promise.isDone() || promise.isCancelled()) return;
        entry.setValue(message);
        promise.setSuccess();
    }

}
